package com.sh.museum.ui;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.sh.museum.R;
import com.sh.museum.base.BaseActivity;
import com.sh.museum.common.Constants;
import com.sh.museum.entities.PlayInfo;

import java.io.IOException;

/**
 * Created by baishiwei on 2015/1/24.
 */
@ContentView(R.layout.audioplayer)
public class AudioPlayer extends BaseActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
    @ViewInject(R.id.top_back_btn)
    ImageButton back;
    @ViewInject(R.id.top_title)
    TextView title;
    @ViewInject(R.id.progress_bar)
    private SeekBar seekbar;
    @ViewInject(R.id.has_played)
    private TextView played;
    @ViewInject(R.id.total_duration)
    private TextView total;
    @ViewInject(R.id.button_play)
    private ImageButton playBtn;
    private MediaPlayer audioPlayer = null;
    private final int PROGRESS_CHANGED = 0;
    @ViewInject(R.id.content)
    private WebView content;
    private String path;
    private String titleInfo;
    private String playNum;
    private boolean isPaused;
    private IntentFilter filter;
    public static AudioPlayer instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        instance = this;
        Constants.PLAYER_FLAG = true;
        getPlayInfo();
        initView();
        init_Intent();
    }

    private void getPlayInfo() {
        Bundle bundle = getIntent().getExtras();
        PlayInfo msg = (PlayInfo) bundle.get("PlayInfo");
        path = msg.getPath();
        titleInfo = msg.getInfo();
        playNum = msg.getNum();
    }

    private void initView() {
        title.setText(titleInfo);
        title.setSelected(true);
        WebSettings webSettings = content.getSettings();
        webSettings.setJavaScriptEnabled(true);
        content.setBackgroundColor(Color.TRANSPARENT);
        content.loadUrl("file:///" + path.replace("mp3", "html"));
        audioPlayer = new MediaPlayer();
        audioPlayer.reset();
        try {
            audioPlayer.setDataSource(path);
            audioPlayer.prepare();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        audioPlayer.setOnPreparedListener(this);
        audioPlayer.setOnCompletionListener(this);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int value = seekbar.getProgress();
                audioPlayer.seekTo(value);
                myHandler.sendEmptyMessage(PROGRESS_CHANGED);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                myHandler.removeMessages(PROGRESS_CHANGED);
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                myHandler.removeMessages(PROGRESS_CHANGED);
            }
        });
    }

    private void init_Intent() {
        filter = new IntentFilter();
        filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        filter.addAction("android.intent.action.PHONE_STATE");
       // filter.addAction(Constants.PLAY_INTENT);
        registerReceiver(phoneReceiver, filter);
    }

    /**
     * 通话状态监听
     */
    BroadcastReceiver phoneReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
                //去电
                System.out.println("去电");
                if (audioPlayer.isPlaying()) {
                    audioPlayer.pause();
                    playBtn.setBackgroundResource(R.drawable.play);
                    isPaused = true;
                }
            } else {
                //来电
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Service
                        .TELEPHONY_SERVICE);
                tm.listen(new PhoneStateListener() {
                    @Override
                    public void onCallStateChanged(int state, String incomingNumber) {
                        super.onCallStateChanged(state, incomingNumber);
                        switch (state) {
                            case TelephonyManager.CALL_STATE_IDLE:
                                //挂断
                                System.out.println("挂断");
                                if (isPaused) {
                                    audioPlayer.start();

                                    playBtn.setBackgroundResource(R.drawable.pause);
                                } else {
                                    audioPlayer.pause();
                                    playBtn.setBackgroundResource(R.drawable.play);
                                }
                                break;
                            case TelephonyManager.CALL_STATE_OFFHOOK:
                                //通话
                                System.out.println("通话");
                                if (audioPlayer.isPlaying()) {
                                    audioPlayer.pause();
                                    playBtn.setBackgroundResource(R.drawable.play);
                                    isPaused = true;
                                }
                                break;
                            case TelephonyManager.CALL_STATE_RINGING:
                                //响铃
                                System.out.println("响铃");
                                if (audioPlayer.isPlaying()) {
                                    audioPlayer.pause();
                                    playBtn.setBackgroundResource(R.drawable.play);
                                    isPaused = true;
                                }
                                break;
                        }
                    }
                }, PhoneStateListener.LISTEN_CALL_STATE);
            }
        }
    };
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
                String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            } else {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                switch (tm.getCallState()) {
                    case TelephonyManager.CALL_STATE_RINGING:
                        if (isPaused) {
                            audioPlayer.start();
                            playBtn.setBackgroundResource(R.drawable.pause);
                        } else {
                            audioPlayer.pause();
                            playBtn.setBackgroundResource(R.drawable.play);
                        }
                        isPaused = !isPaused;
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        if (isPaused) {
                            audioPlayer.start();
                            playBtn.setBackgroundResource(R.drawable.pause);
                        } else {
                            audioPlayer.pause();
                            playBtn.setBackgroundResource(R.drawable.play);
                        }
                        isPaused = !isPaused;
                        break;
                }
            }
            if (intent.getAction().equals(Constants.PLAY_INTENT)) {
                PlayInfo msg = (PlayInfo) intent.getExtras().getSerializable("PlayInfo");
                path = msg.getPath();
                playNum = msg.getNum();
                title.setText(msg.getInfo());
                content.loadUrl("file:///" + path.replace("mp3", "html"));
                if (audioPlayer != null && audioPlayer.isPlaying()) {
                    audioPlayer.pause();
                    audioPlayer.release();
                    audioPlayer = null;
                }
                audioPlayer = new MediaPlayer();
                audioPlayer.reset();
                try {
                    audioPlayer.setDataSource(path);
                    audioPlayer.prepare();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                audioPlayer.setOnPreparedListener(AudioPlayer.this);
                audioPlayer.setOnCompletionListener(AudioPlayer.this);
            }
        }

    };

    @Override
    public void onCompletion(MediaPlayer mp) {
        defaultFinish();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        int i = mp.getDuration();
        seekbar.setMax(i);
        i /= 1000;
        int minute = i / 60;
        int second = i % 60;
        minute %= 60;
        total.setText(String.format("%02d:%02d", minute, second));
        played.setText("00:00");
        playBtn.setBackgroundResource(R.drawable.pause);
        seekbar.setProgress(mp.getCurrentPosition());
        audioPlayer.start();
        myHandler.sendEmptyMessage(PROGRESS_CHANGED);
    }

    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PROGRESS_CHANGED:
                    int i = audioPlayer.getCurrentPosition();
                    i /= 1000;
                    int minute = i / 60;
                    int second = i % 60;
                    minute %= 60;
                    played.setText(String.format("%02d:%02d", minute, second));
                    seekbar.setProgress(i * 1000);
                    sendEmptyMessageDelayed(PROGRESS_CHANGED, 1000);
                    break;
            }
        }
    };

    @OnClick(R.id.button_play)
    public void play(View view) {
        if (isPaused) {
            audioPlayer.start();
            playBtn.setBackgroundResource(R.drawable.pause);
        } else {
            audioPlayer.pause();
            playBtn.setBackgroundResource(R.drawable.play);
        }
        isPaused = !isPaused;
    }

    @OnClick(R.id.top_back_btn)
    public void back(View view) {
        defaultFinish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (audioPlayer!=null){
            audioPlayer.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Constants.PLAYER_FLAG = false;
        myHandler.removeMessages(PROGRESS_CHANGED);
        unregisterReceiver(phoneReceiver);
        if (audioPlayer != null) {
            audioPlayer.stop();
            audioPlayer.release();
        }
    }

}
